<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no">
<title>Context Monitor</title>
<link rel="stylesheet" type="text/css" href="jquery/jquery.mobile-1.0a4.1.css" />
<style type="text/css">
	#map { width: 320px; height: 400px }
</style>
<script src="jquery/jquery-1.6.1.min.js"></script>
<script src="jquery/jquery.mobile-1.0a4.1.js"></script>
<script type="text/javascript" src="http://apis.daum.net/maps/maps3.js?apikey=fdedf555ead724e65234ad4eb1ccb6760c6a6f1a"></script>
<script type="text/javascript">
	var map = null;
	var myMarker = null;
	var infoWindow = null;

	var curLat = null;
	var curLng = null;

	var eventMarker = null;
	var eventInfoWnd = null;
	
	var fb_ids = null;
	
	var timer = null;
	function distance(lat1, lon1, lat2, lon2) {
		var radlat1 = Math.PI * lat1/180;
		var radlat2 = Math.PI * lat2/180;
		var radlon1 = Math.PI * lon1/180;
		var radlon2 = Math.PI * lon2/180;
		var theta = lon1-lon2;
		var radtheta = Math.PI * theta/180;
		var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
		dist = Math.acos(dist);
		dist = dist * 180/Math.PI;
		dist = dist * 60 * 1.1515;
		return dist * 1.609344 * 1000;
	} 
	function monitorContext() {
		navigator.geolocation.getCurrentPosition(function(pos) {
			if (sessionStorage['user_id'] != 'test') {
			curLat += 0.0002;
			curLng += 0.0002;
			}
			var distToBusStation = distance(curLat, curLng, 37.569309407587824, 126.98015931867272);
			var position = new daum.maps.LatLng(curLat, curLng);
			map.setCenter(position);
			myMarker.setPosition(position);
			infoWindow.setContent('<p style="margin:7px 12px;font-size:12px">위도:'+curLat+'<br />경도:'+curLng+'</p>');
			//infoWindow.setContent('<p style="margin:7px 12px;font-size:12px">거리차: '+distToBusStation+'m</p>');
			infoWindow.setPosition(position);
/*
			console.log(sessionStorage['isBusNoticed']);
			if (distToBusStation <= 400 && sessionStorage['isBusNoticed'] == 'false') {
				sessionStorage['isBusNoticed'] = 'true';
				$.mobile.changePage("bus_alarm.html", "pop", false, false);
			}
*/			
			// 근처 할인정보 가져오기 (창천동)
/*
			$.getJSON("get_sale_events.php", {lat: curLat, lng: curLng, radius: "150"}, function(data) {
				$.each(data, function(events, event) {
					//console.log(event.distance);
					if (event.item.match(sessionStorage['interest']) != null) {
						var position = new daum.maps.LatLng(event.lat, event.lng);
						if (!eventMarker) {
							eventMarker = new daum.maps.Marker({ position: position });
							eventMarker.setMap(map);
						}
						if (!eventInfoWnd) {
							eventInfoWnd = new daum.maps.InfoWindow({ content: '<h5>'+event.shop_name+'</h5><p style="margin:3px 9px;font-size:12px">'+event.event+'</p>'});
							eventInfoWnd.open(map, eventMarker);
						}
					}
				});
			}, "json");
*/			
			$.post("session.php", {user_id: sessionStorage['user_id'], lat: curLat, lng: curLng});
			// 근처에 접근한 사람 facebook id 줘라
			$.getJSON("get_adjacency_user.php", {user_id: sessionStorage['user_id'], lat: curLat, lng: curLng, radius: "100"}, function(data) {
				$.each(data, function(adjUsers, adjUser) {
					for (var i in fb_ids) {
						console.log(fb_ids[i] + " " + adjUser.fb_id);
						if (fb_ids[i] == adjUser.fb_id) {
							// 적절한 처리
							sessionStorage['latest_contact_fb_id'] = adjUser.fb_id;
							sessionStorage['latest_contact_fb_lat'] = adjUser.lat;
							sessionStorage['latest_contact_fb_lng'] = adjUser.lng;
							$.mobile.changePage('#near_friend_alarm_dialog', "pop", false);
							clearTimeout(timer);
							break;
						}
					}
				});				
			});
		});
		timer = setTimeout(monitorContext, 1000);
	}
	$('document').ready(function() {
		var ids = sessionStorage['fb_friend_ids'];
		if (ids) {
			fb_ids = ids.split(",");
			console.log(fb_ids);
		}
		
		navigator.geolocation.getCurrentPosition(function(pos) {
			if (sessionStorage['user_id'] == 'test') {
			curLat = pos.coords.latitude + 0.0002*10;
			curLng = pos.coords.longitude + 0.0002*10;
			}
			else {
			curLat = pos.coords.latitude;
			curLng = pos.coords.longitude;
			}
			var position = new daum.maps.LatLng(curLat, curLng);
			map = new daum.maps.Map(document.getElementById('map'), {
									center: position,
									level: 3,
									mapTypeId: daum.maps.MapTypeId.HYBRID
								  });
			myMarker = new daum.maps.Marker({ position: position });
			myMarker.setMap(map);
			infoWindow = new daum.maps.InfoWindow({ content: '<p style="margin:7px 12px;font-size:12px">위도:'+curLat+'<br />경도:'+curLng+'</p>'});
			infoWindow.open(map, myMarker);
			
			timer = setTimeout(monitorContext, 1000);
		});
	});
	
	var adjFriendMarker = null;
	var adjInfoWnd = null;
	function placeAdjFriend() {
		console.log(parseFloat(sessionStorage['latest_contact_fb_lat']));
		console.log(parseFloat(sessionStorage['latest_contact_fb_lng']));
		var position = new daum.maps.LatLng(parseFloat(sessionStorage['latest_contact_fb_lat']),
											parseFloat(sessionStorage['latest_contact_fb_lng']));
		adjFriendMarker = new daum.maps.Marker({ position: position });
		adjFriendMarker.setMap(map);
		var id = sessionStorage['latest_contact_fb_id'];
		adjInfoWnd = new daum.maps.InfoWindow({ content: '<p style="margin:3px 9px;font-size:12px">친구의 말: 하이 ㅋㅋ</p>'});
		adjInfoWnd.open(map, adjFriendMarker);
		
		infoWindow.setContent('<input type="text" value="대화를 입력하세요" onclick="this.value=\'\';" />');
	}
</script>
</head>
<body>
<div data-role="page" data-theme="b">
	<div data-role="header">
		<h1>Context Monitor</h1>
	</div>
	<div id="map" data-role="content" data-theme="c"></div>
	<div data-role="footer" data-theme="a">
		<div data-role="navbar">
			<ul>
				<li><a rel="external" href="service_list.html" data-icon="grid">Services</a></li>
				<li><a rel="external" href="preference.html" data-icon="gear">Preference</a></li>
			</ul>
		</div>
	</div>
</div>
<div data-role="page" id="near_friend_alarm_dialog" data-theme="b">
	<div data-role="header">
		<h1>근처의 친구 접근 알림</h1>
	</div>
	<div data-role="content" data-theme="c">
		<h1>근처의 친구 알림</h1>
		<h3>친구가 인접한 곳에 접근했습니다</h3>
		<p>친구가 50m이내에 있습니다. 친구와 대화를 나누시겠습니까?</p>
		<div data-inline="true">
			<a href="context_monitor.html" data-role="button" data-rel="back" data-theme="b" onclick="placeAdjFriend();">네</a>
			<a href="context_monitor.html" data-role="button" data-rel="back">아니오</a>
		</div>
	</div>
</div>
</body>
</html>